import { defineStore } from "pinia";
import Local from "tools-utils/storage";
import { router } from "@/router";
// 从消息中心引入连接控制
import { ensureConnected, disconnect, setAuthToken } from "@/core/registerMessageHandlers";
/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore("userInfoStore", {
  state: () => ({
    token: "",
    userInfo: {},
    roles: [],
    auths: [],
    // 第一步登录后返回的候选品牌/客户（用于弹窗展示）
    loginCandidates: [], // [{ id, sign, customer: { id, customerName, tenantId, ... } }, ...]
  }),
  getters: {
    // 多个权限验证，满足一个则显示
    hasAuth: authKeys => Array.isArray(authKeys) && this.auths.some(key => authKeys.includes(key)),
    // 多个权限验证，全部满足则显示
    hasAuthAll: authKeys => Array.isArray(authKeys) && authKeys.every(key => this.auths.includes(key)),
  },
  actions: {
    /** 内部：统一处理登录结果 */
    _consumeChooseResp(data = {}) {
      const token = data.token || "";
      this.token = token;
      this.userInfo = data;
      this.roles = Array.isArray(data.roles) ? data.roles : [];

      Local.set("token", token);
      Local.set("userInfo", this.userInfo);
      Local.set("roles", this.roles);
    },

    /** 第一步：密码登录 -> 返回候选客户列表 */
    async LoginByPwd(payload = {}) {
      const res = await Api.login.LoginByPwd({
        mobile: payload.mobile,
        pass: payload.password,
        code: payload.imgCode,
        cid: payload.captchaId,
      });
      const list = res?.data ?? [];
      this.loginCandidates = Array.isArray(list) ? list : [];
      // 第一步不落 token；只返回候选列表，供页面弹窗使用
      return this.loginCandidates;
    },

    /** 第一步：短信登录 -> 返回候选客户列表 */
    async LoginByCode(payload = {}) {
      const res = await Api.login.LoginByCode({
        mobile: payload.mobile,
        code: payload.smsCode,
      });
      const list = res?.data ?? [];
      this.loginCandidates = Array.isArray(list) ? list : [];
      return this.loginCandidates;
    },

    /** 第二步：选择客户 -> 返回 token 和完整用户信息 */
    async ChooseUser({ id, sign, tenantId }) {
      const res = await Api.login.LoginChooseUser({ id, sign, tenantId });
      const data = res?.data ?? {};
      this._consumeChooseResp(data);
      return data;
    },

    /** 应用启动恢复：若本地已有 token，恢复用户信息并连上 WS */
    RestoreSessionAndWS() {
      const token = Local.get("token") || "";
      if (token) {
        this.token = token;
        this.userInfo = Local.get("userInfo") || {};
        this.roles = Local.get("roles") || [];
        try {
          setAuthToken(token);
          ensureConnected();
        } catch (e) {
          console.warn("[MsgCenter] ensureConnected on boot failed:", e);
        }
      }
    },

    // 获取权限点
    GetUserAuths() {
      return new Promise((resolve, reject) => {
        Api.user
          .GetUserAuths()
          .then(res => {
            const data = res.data || [];
            this.auths = data || [];
            // 存储 权限点 到浏览器缓存
            Local.set("user-auths", this.auths);
            resolve(res);
          })
          .catch(reject);
      });
    },

    // 直接清缓存并跳转登录
    Logout() {
      try {
        disconnect(); // 主动断开，停止重连并清订阅
      } catch (e) {
        console.warn("[MsgCenter] disconnect on logout error:", e);
      }

      // 1) 清 pinia 状态（配合 persist 会同步覆盖本地持久化）
      if (typeof this.$reset === "function") {
        this.$reset();
      } else {
        this.token = "";
        this.userInfo = {};
        this.roles = [];
        this.auths = [];
        this.loginCandidates = [];
      }

      // 2) 清除所有本地缓存（你们的 Local.clear 会清空 localStorage）
      try {
        Local.clear();
      } catch (e) {
        console.warn("[Logout] Local.clear error:", e);
        // 兜底：即使出错也继续跳转
      }

      // 3) 直接跳登录页（不带 redirect）
      router.replace("/login");
    },
  },
  persist: true, // 开启自动缓存
});
